package com.chat.service;

import com.chat.Local;
import com.chat.common.*;
import com.chat.io.ChangeImage;
import com.chat.io.SetFile;
import com.chat.view.*;
import javafx.application.Platform;
import javafx.scene.control.Alert;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Objects;
import static com.chat.view.MainWindowController.chat;
import static com.chat.view.MainWindowController.friend;
import static com.chat.view.AddGroupController.addgroup;

/*
    客户端连接服务端的线程
 */
public class ClientConnectServerThread extends Thread{
        private static Socket socket;
        private ObjectInputStream ois;
        private ObjectOutputStream oos;
        public Boolean state=true;

        public ClientConnectServerThread(Socket socket){
              this.socket=socket;
        }

        public Message receive() {
        Message message = null;
        try {
            ois = new ObjectInputStream(socket.getInputStream());
            message = (Message) ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return message;
    }

        public void send(Message message) {
        try {
            oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(message);
            oos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Override
    public void run() {

         while(state) {
             System.out.println("客户端线程，等待读取从服务器发送的消息");
             Message message = receive();
             if (message.getMesType().equals(MessageType.MESSAGE_USER_ALL)) {//获取当前用户信息
                 System.out.println("获取到用户信息");
                 User user = (User) message.getData();
                 Local.user = user;
                 ChangeImage ci=new ChangeImage();
                 byte[] b= (byte[]) user.getHeadpicture();
                 ci.set(user.getUsername(),b);
             }
             if (message.getMesType().equals(MessageType.MESSAGE_GET_FRIEND_LIST)) {//获取当前好友列表
                 ArrayList<User> a = (ArrayList<User>) message.getData();
                 GetFriendList gfl = new GetFriendList();
                 gfl.SetFriendList(a);
             }
             if (message.getMesType().equals(MessageType.MESSAGE_SEARCH_FRIEND_SUCCEED)) {//搜索id成功
                 User user = new User();
                 user = (User) message.getData();
                 SearchFriend sf = new SearchFriend();
                 sf.setFriend(user);
             }
             if(message.getMesType().equals(MessageType.MESSAGE_SERACH_MYSELF)){//用户搜索了自己
                 Platform.runLater(() -> {
                     ((javafx.scene.control.Label) AddFriendView.$("tishi")).setText("不能搜索自己！");
                 });
             }
             if (message.getMesType().equals(MessageType.MESSAGE_SEARCH_FRIEND_FAIL)) {//搜素id不存在
                 Platform.runLater(() -> {
                     ((javafx.scene.control.Label) AddFriendView.$("tishi")).setText("用户id不存在！");
                 });
             }
             if (message.getMesType().equals(MessageType.MESSAGE_SEARCH_FRIEND_REPEAT)){//想要添加的好友已存在
                 Platform.runLater(() -> {
                     ((javafx.scene.control.Label) AddFriendView.$("tishi")).setText("你已添加该用户！");
                 });
            }
             if(message.getMesType().equals(MessageType.MESSAGE_SEND_FRIEND_APPLY_SUCCEED)) {//表示好友申请发送成功
                 Platform.runLater(() -> {
                      Alert alert = new Alert(Alert.AlertType.INFORMATION);
                      alert.setTitle("提示");
                      alert.setHeaderText("恭喜");
                      alert.setContentText("好友申请已发送！");
                      alert.showAndWait();
                 });
             }
             if(message.getMesType().equals(MessageType.MESSAGE_SEND_REPEAT)){//表示用户多次发送申请
                 Platform.runLater(() -> {
                     ((javafx.scene.control.Label) AddFriendView.$("tishi")).setText("你已经给该用户发送过申请了！");
                 });
             }
             if(message.getMesType().equals(MessageType.MESSAGE_NO_VERIFY_MESSAGE)){//表示当前用户没有验证消息
                 Platform.runLater(()-> {
                     ((javafx.scene.control.Label) VerifyMessageView.$("blanktishi")).setText("当前没有验证消息");
                 });
             }
             if(message.getMesType().equals(MessageType.MESSAGE_GET_VERIFY_MESSAGE_SUCCEED)) {//表示成功提取到验证消息
                 ArrayList<User> a = (ArrayList<User>) message.getData();
                 GetVerifyMessage gvf=new GetVerifyMessage();
                 gvf.setverifymessage(a);
             }
             if(message.getMesType().equals(MessageType.MESSAGE_ADD_FRIEND_SUCCEED)){//表示添加好友成功
                     System.out.println("好友添加成功");
                     User user= (User) message.getData();
                     AddFriend af=new AddFriend();
                     af.setfriend(user);
             }
             if(message.getMesType().equals(MessageType.MESSAGE_RECEIVE_ADD_FRIEND)){//表示自己发出去的好友申请已被同意
                    User user= (User) message.getData();
                    AddFriend af=new AddFriend();
//                    af.setfriend1();
                 Platform.runLater(new Runnable() {
                     @Override
                     public void run() {
                          friend.add(new FriendListData(user.getNickname(),user.getUsername(),user.getQianming(),"1","1"));
                     }
                 });
             }
             if(message.getMesType().equals(MessageType.MESSAGE_GET_FRIEND_MESSAGE)){//获取当前好友的详细信息
                     Local.friend= (User) message.getData();
             }
             if(message.getMesType().equals(MessageType.MESSAGE_PRIVATE_CHAT_TEXT)){//如果接受端也打开了与发送端的聊天框，就将消息加入到listview
                 System.out.println("接受到了消息");
                 ChatMsg cm= (ChatMsg) message.getData();
                   if(Objects.equals(Local.receive, cm.getSenderid())){
                       Platform.runLater(()-> {
//                           ((javafx.scene.control.ListView) MainWindowView.$("chatlist")).getItems().clear();
                       });
                       Platform.runLater(new Runnable() {
                           @Override
                           public void run() {
                               chat.add(new ChatListData(cm.getSendernickname(),cm.getContent(),cm.getSenderid(),"1", cm.getTime()));
                               ((javafx.scene.control.ListView) MainWindowView.$("chatlist")).scrollTo(1000);
                           }
                       });
                   }

             }
             if(message.getMesType().equals(MessageType.MEESAGE_DEL_FRIEND)){//接受端实时删除好友列表中的好友
                 User user= (User) message.getData();
                 int line=0;
                 Iterator<FriendListData> iter=friend.iterator();
                 while(iter.hasNext()){
                     FriendListData friendListData=(FriendListData) iter.next();
                     System.out.println(friendListData.getId());
                     if(friendListData.getId().equals(user.getDelid())){
                         friend.remove(line);
                         break;
                     }
                     line++;
                 }
                   DelFriend df=new DelFriend();
                   df.setfriend();
             }
             if(message.getMesType().equals(MessageType.MESSAGE_GET_HISTORY_MSG)){//获取消息记录
                 ArrayList<ChatMsg> a = (ArrayList<ChatMsg>) message.getData();
                    GetHistoryMsg ghm=new GetHistoryMsg();
                    ghm.sethistorymsg(a);
             }
             if(message.getMesType().equals(MessageType.MESSAGE_GET_GROUP_LIST)){//拉取群列表
                 ArrayList<Group> a=(ArrayList<Group>) message.getData();
                  GetGroupList ggl=new GetGroupList();
                  ggl.setGroupList(a);
             }
             if(message.getMesType().equals(MessageType.MESSAGE_GET_GROUP_MSG)){//获取群的详细信息
                    Group group= (Group) message.getData();
                 System.out.println(group.getName());
                    Local.group=group;
             }
             if(message.getMesType().equals(MessageType.MESSAGE_SEARCH_GROUP_FAIL)){//搜索的群聊id不存在
                 Platform.runLater(new Runnable() {
                     @Override
                     public void run() {
                         Alert alert = new Alert(Alert.AlertType.INFORMATION);
                         alert.setTitle("提示");
                         alert.setHeaderText("警告");
                         alert.setContentText("群聊id不存在！");
                         alert.showAndWait();
                     }
                 });
             }
             if(message.getMesType().equals(MessageType.MESSAGE_SEARCH_GROUP_SUCCEED)){//搜索群聊id成功
                   Group group= (Group) message.getData();
                 Platform.runLater(new Runnable() {
                     @Override
                     public void run() {
                        addgroup.add(new AddListData(group.getName(),group.getInfo()));
                         ((javafx.scene.control.Button) AddGroupView.$("add")).setDisable(false);
                     }
                 });
             }
             if(message.getMesType().equals(MessageType.MESSAGE_SEND_GROUP_APPLY_REPEAT)){//重复发送群聊申请
                 Platform.runLater(new Runnable() {
                     @Override
                     public void run() {
                         Alert alert = new Alert(Alert.AlertType.INFORMATION);
                         alert.setTitle("提示");
                         alert.setHeaderText("警告");
                         alert.setContentText("你已经给该群聊发送过申请了！");
                         alert.showAndWait();
                     }
                 });
             }
             if(message.getMesType().equals(MessageType.MESSAGE_SEARCH_GROUP_REPEAT)){
                 Platform.runLater(new Runnable() {
                     @Override
                     public void run() {
                         Alert alert = new Alert(Alert.AlertType.INFORMATION);
                         alert.setTitle("提示");
                         alert.setHeaderText("警告");
                         alert.setContentText("您已经是群聊中的成员！");
                         alert.showAndWait();
                     }
                 });
             }
             if(message.getMesType().equals(MessageType.MESSAGE_SEND_GROUP_APPLY_SUCCEED)){
                 Platform.runLater(new Runnable() {
                     @Override
                     public void run() {
                         Alert alert = new Alert(Alert.AlertType.INFORMATION);
                         alert.setTitle("提示");
                         alert.setHeaderText("恭喜");
                         alert.setContentText("已发送加群申请！");
                         alert.showAndWait();
                     }
                 });
             }
             if(message.getMesType().equals(MessageType.MESSAGE_NO_GROUP_VERIFY)){//当前群聊没有验证消息
                 Platform.runLater(new Runnable() {
                     @Override
                     public void run() {
                         ((javafx.scene.control.Label) GroupVerifyView.$("blanktishi")).setText("当前没有验证消息");
                     }
                 });
             }
             if(message.getMesType().equals(MessageType.MESSGE_GET_GROUP_VERIFY_SUCCEED)){//成功获取到当前群聊的验证消息
                 ArrayList<User> a = (ArrayList<User>) message.getData();
                  GetGroupVerify ggv=new GetGroupVerify();
                  ggv.setgroupverify(a);
             }
             if(message.getMesType().equals(MessageType.MESSAGE_RECEIVE_ADD_GROUP_MEMBER)){//表示自己发出去的群聊申请已被同意
                  Group group= (Group) message.getData();
                 Platform.runLater(new Runnable() {
                     @Override
                     public void run() {
                           friend.add(new FriendListData(group.getName(),group.getId(),group.getInfo(),"0","1"));
                     }
                 });
             }
             if(message.getMesType().equals(MessageType.MESSAGE_GROUP_CHAT_TEXT)){//如果其他群成员也打开了这个群聊对话框，就动态添加消息
                       ChatMsg cm= (ChatMsg) message.getData();
                       if(Objects.equals(cm.getGroupid(), Local.receive)){
                           Platform.runLater(new Runnable() {
                               @Override
                               public void run() {
                                   chat.add(new ChatListData(cm.getSendernickname(),cm.getContent(),cm.getSenderid(),"1",cm.getTime()));
                               }
                           });
                       }
             }
             if(message.getMesType().equals(MessageType.MESSAGE_GET_GROUP_HISTROY_MSG)){//获取群聊历史消息
                 ArrayList<ChatMsg> a= (ArrayList<ChatMsg>) message.getData();
                 GetGroupHistoryMsg gghm=new GetGroupHistoryMsg();
                 gghm.set(a);
             }
             if(message.getMesType().equals(MessageType.MESSAGE_GET_GROUP_MEMBER)){//获取当前群聊的成员列表
                    ArrayList<User>a= (ArrayList<User>) message.getData();
                     GetGroupMember ggm=new GetGroupMember();
                     ggm.set(a);
             }
             if(message.getMesType().equals(MessageType.MESSAGE_PRIVATE_CHAT_IMAGE)){//图片私聊接收端全局响应
                 ChatMsg cm= (ChatMsg) message.getData();
                 SetFile sf=new SetFile();
                   sf.set((byte[]) cm.getFile(),cm.getFilename());//将图片下载到本地
                 if(Objects.equals(Local.receive, cm.getSenderid())){//判断接收端是否也打开了与发送端的聊天框
                     Platform.runLater(new Runnable() {
                         @Override
                         public void run() {
                             chat.add(new ChatListData(cm.getSendernickname(),cm.getFilename(),cm.getSenderid(),"2",cm.getTime()));
                         }
                     });
                 }
             }
             if(message.getMesType().equals(MessageType.MESSAG_GROUP_CHAT_IMAGE)){//群聊中发图片的全局响应
                 ChatMsg cm= (ChatMsg) message.getData();
                  SetFile sf=new SetFile();
                  sf.set((byte[]) cm.getFile(),cm.getFilename());
                 if(Objects.equals(cm.getGroupid(), Local.receive)){//判断其他群成员是否也打开了当前群聊的聊天框
                     Platform.runLater(new Runnable() {
                         @Override
                         public void run() {
                               chat.add(new ChatListData(cm.getSendernickname(),cm.getFilename(),cm.getSenderid(),"2",cm.getTime()));
                         }
                     });
                 }
             }
             if(message.getMesType().equals(MessageType.MESSAGE_ONLINE)){//有好友上线了
                 User user= (User) message.getData();
                  FriendStatus fs=new FriendStatus();
                  fs.set(user.getUsername(),"1");
             }
             if(message.getMesType().equals(MessageType.MESSAGE_EXIT)){//有好友下线了
                  User user= (User) message.getData();
                   FriendStatus fs=new FriendStatus();
                   fs.set(user.getUsername(),"0");
             }
             if(message.getMesType().equals(MessageType.MESSAGE_PRIVATE_CHAT_FILE)){//文件私聊接收端全局响应
                 ChatMsg cm= (ChatMsg) message.getData();
                 if(Objects.equals(Local.receive, cm.getSenderid())){
                     Platform.runLater(new Runnable() {
                         @Override
                         public void run() {
                             chat.add(new ChatListData(cm.getSendernickname(),cm.getAddress(),cm.getFilename(),cm.getSenderid(),cm.getTime(),"3"));
                         }
                     });
                 }
             }
             if(message.getMesType().equals(MessageType.MESSAGE_GET_COMMON_PHARSE)){//获取常用语
                    ArrayList<String>a= (ArrayList<String>) message.getData();
                     Local.commonlist=a;
             }
             if(message.getMesType().equals(MessageType.MESSAGE_DOWNLOAD_FILE)){
                      ChatMsg cm= (ChatMsg) message.getData();
                      FileService fileService=new FileService();
                      fileService.download((byte[]) cm.getFile(),cm.getCount(),cm.getSenderid());
             }
             if(message.getMesType().equals(MessageType.MESSAGE_MERGE_FILE)){
                      ChatMsg cm= (ChatMsg) message.getData();
                      FileService fs=new FileService();
                      fs.merger(cm.getAddress(),cm.getCount(),cm.getSenderid());
             }
             if(message.getMesType().equals(MessageType.MESSAGE_GROUP_CHAT_FILE)){//群聊中发文件的全局响应
                 ChatMsg cm= (ChatMsg) message.getData();
                 if(Objects.equals(cm.getGroupid(), Local.receive)){//判断其他群成员是否也打开了当前群聊的聊天框
                     Platform.runLater(new Runnable() {
                         @Override
                         public void run() {
                             chat.add(new ChatListData(cm.getSendernickname(),cm.getAddress(),cm.getFilename(),cm.getSenderid(),cm.getTime(),"3"));
                         }
                     });
                 }
             }
         }


    }
    public Socket getSocket(){
        return socket;
    }
}
